package com.taint.callgraph;


import java.util.Arrays;

public class CallStack {

    private static int MAXSTACK=10;

    public static StackTraceElement[] createCallStack(int stackStartPos) {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        StackTraceElement[] selfCallStack = new StackTraceElement[stackTraceElements.length - stackStartPos];
        if (stackTraceElements.length - stackStartPos >= 0) {
            System.arraycopy(stackTraceElements, stackStartPos, selfCallStack, 0, stackTraceElements.length - stackStartPos);
        }
        return selfCallStack;
    }




    public static String PrintStack(StackTraceElement[] stackTraceElements){
        StringBuilder sb=new StringBuilder();
        if(stackTraceElements==null){
            return null;
        }
        int num=0;
        for(StackTraceElement element:filter(stackTraceElements)){
            if(num>=MAXSTACK){
                return null;
            }

            String stack="%s(%s:%s)--%s";
            stack=String.format(stack,element.getClassName(),element.getFileName(),element.getLineNumber(),element.getMethodName());
            sb.append(stack).append(" ");
            num++;
        }

        return sb.toString();
    }


    public static StackTraceElement[] filter(StackTraceElement[] trace) {
        int i = 0;
        // 去除插件本身调用栈
        while (i < trace.length && (trace[i].getClassName().startsWith("com.taint")
                || trace[i].getClassName().contains("reflect"))) {
            i++;
        }
        return Arrays.copyOfRange(trace, i, trace.length);
    }


}
